package com.zline.foodraise.ui.activity;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.zline.foodraise.R;
import com.zline.foodraise.baidu.LocationUtil;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.db.DatabaseHelper;
import com.zline.foodraise.db.dao.CityDao;
import com.zline.foodraise.db.dao.ProvinceDao;
import com.zline.foodraise.entity.AppPref_;
import com.zline.foodraise.entity.City;
import com.zline.foodraise.entity.Province;
import com.zline.foodraise.util.FileUtils;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.TUtil;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.sharedpreferences.Pref;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by heshantao on 15/10/14.
 * 启动页
 */
@EActivity(R.layout.activity_splash)
public class SplashActivity extends ZlineActivity implements BDLocationListener {
    private static final String LOG_TAG = SplashActivity.class.getSimpleName();
    boolean isFirst;
    DatabaseHelper helper;
    @Bean
    CityDao cityDao;
    @Bean
    ProvinceDao provinceDao;
    @Pref
    AppPref_ appPref;
    @Bean
    LocationUtil locationUtil;
    List<City> list;
    BDLocation loaction;


    @AfterInject
    void doSomeAfterInject() {
        initData();
        initLocation();
        requestLocation();
    }

    void initData() {
        //是否是第一次
        isFirst = appPref.isFirest().get();
        if (isFirst) {
            saveCityAndProvince();
            appPref.edit().isFirest().put(false).apply();
        }
    }

    //将城市和省份信息存入数据库
    @Background
    void saveCityAndProvince() {
        getHelper();
        cityDao.setHelper(helper);
        saveCity();
        provinceDao.setHelper(helper);
        saveProvince();

    }

    //slite 实例
    void getHelper() {
        if (helper == null) {
            helper = OpenHelperManager.getHelper(this, DatabaseHelper.class);
        }
    }


    //解析城市列表
    void saveCity() {
        InputStream is = getResources().openRawResource(R.raw.city);
        String cityInfo = FileUtils.readFile(is);
        List<City> list = new ArrayList<City>();
        Gson gson = new Gson();
        JsonElement jsonElement = new JsonParser().parse(cityInfo);
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        JsonElement jsonElementCity = jsonObject.get(Constant.City);
        if (jsonElementCity.isJsonArray()) {
            JsonArray jsonArray = jsonElementCity.getAsJsonArray();//转为数组
            for (Iterator iter = jsonArray.iterator(); iter.hasNext(); ) {
                JsonObject obj = (JsonObject) iter.next();
                final City city = gson.fromJson(obj, City.class);//方法二：灵活使用Gson取数据
                cityDao.add(city);
            }

        }
    }


    //解析省份列表
    void saveProvince() {
        InputStream is = getResources().openRawResource(R.raw.province);
        String cityInfo = FileUtils.readFile(is);
        Gson gson = new Gson();
        JsonElement jsonElement = new JsonParser().parse(cityInfo);
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        JsonElement jsonElementCity = jsonObject.get(Constant.PROVINCE);
        if (jsonElementCity.isJsonArray()) {
            JsonArray jsonArray = jsonElementCity.getAsJsonArray();//转为数组
            for (Iterator iter = jsonArray.iterator(); iter.hasNext(); ) {
                JsonObject obj = (JsonObject) iter.next();
                final Province province = gson.fromJson(obj, Province.class);//方法二：灵活使用Gson取数据
                provinceDao.add(province);
            }

        }
    }


    //获得城市Id
    long getCityId(String cityName) {
        getHelper();
        cityDao = new CityDao();
        cityDao.setHelper(helper);
        list = cityDao.findAll();
        for (City city : list) {
            LUtil.i(LOG_TAG,"___________cityName_____"+cityName);
            if (cityName.equals(city.getCityName())) {
                return city.getCityId();
            }
        }
        return 0;
    }

    //初始化定位信息
    void initLocation() {
        locationUtil.setDBLocationListener(this);
        locationUtil.initLocationClient();
        locationUtil.startLocation();
    }

    //请求定位
    void requestLocation() {
        locationUtil.requestLocation();
        checkLocationFaile();
    }

    //判断定位是否成功(避免过长时间在主线程停留)
    @Background(delay = 5000)
    void checkLocationFaile(){
        //定位失败
        if(loaction==null){
            locationUtil.stopLocation();
            MainActivity_.intent(this).start();
        }
    }


    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        loaction=bdLocation;
        if (bdLocation == null) {
            TUtil.showShort(this, R.string.fail_location);
            MainActivity_.intent(this).start();
        }
        if (bdLocation.hasAddr()) {
            //纬度
            double latPoint = bdLocation.getLatitude();
            //精度
            double lonPoint = bdLocation.getLongitude();
            //城市名
            String cityName = bdLocation.getCity();
            //城市ID
            long cityId = getCityId(bdLocation.getCity());
            LUtil.i(LOG_TAG, "________onReceiveLocation______" +
                    latPoint + "___城市名___" + cityName + "__城市ID____" + cityId+"_____lonPoint____"+lonPoint);

            Set<String> tags = new HashSet<String>();
            tags.add(cityId + "");
            //JPushInterface.setAliasAndTags(this, null, tags, mAliasCallback);

            //地址详情
            String userAddress = bdLocation.getAddrStr();
            appPref.edit().city().put(cityName).apply();
            appPref.edit().cityId().put(cityId).apply();
            appPref.edit().latPoint().put(latPoint + "").apply();
            appPref.edit().lonPoint().put(lonPoint + "").apply();
            appPref.edit().userAddress().put(userAddress).apply();
        } else {
            TUtil.showShort(this, R.string.fail_location);
        }
        MainActivity_.intent(this).start();
    }


    //推送设置标签回调
    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    LUtil.i(LOG_TAG, logs);
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    LUtil.i(LOG_TAG, logs);
                    setTags(tags);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    LUtil.i(LOG_TAG, logs);
            }
        }
    };

    //设置标签
    @Background(delay = 60000)
    void setTags(Set<String> tags) {
        JPushInterface.setAliasAndTags(this, null, tags, mAliasCallback);
    }


    @Override
    protected void onStop() {
        super.onStop();
        locationUtil.stopLocation();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (helper != null) {
            OpenHelperManager.releaseHelper();
            helper = null;
        }
    }
}
